import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/stock_quant.dart';
import 'package:flutter_admin/models/user_info.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/stock_picking_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/http_util.dart';
import 'package:flutter_admin/pages/odoo/material/workshop_transfer/transfer_library.dart';
import 'package:flutter_admin/pages/odoo/stock_picking/stock_picking_dialog.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:quiver/strings.dart';

class ERPSearchOnTimeList extends StatefulWidget {
  ERPSearchOnTimeList({Key? key}) : super(key: key);
  @override
  _ERPSearchOnTimeListState createState() => _ERPSearchOnTimeListState();
}

class _ERPSearchOnTimeListState extends State<ERPSearchOnTimeList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
  PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  String? partNo = null;


  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      // _query();
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 180,
            label: '零件号',
            value: partNo,
            onSaved: (v) {
              partNo = v;
            },
            validator: (v) {
              return v!.isEmpty ? S.of(context).required : null;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('零件号')),
        DataColumn(label: Text('零件描述')),
        DataColumn(label: Text('库位号')),
        DataColumn(label: Text('库位描述')),
        DataColumn(label: Text('仓库')),
        DataColumn(label: Text('库位类型')),
        DataColumn(label: Text('批号')),
        DataColumn(label: Text('现有数量')),
        DataColumn(label: Text('预留数量')),
        DataColumn(label: Text('可用数量')),
        DataColumn(label: Text('计量单位')),
        DataColumn(label: Text('单位描述')),
        DataColumn(label: Text('接收日期')),
        DataColumn(label: Text('上次活动日期')),
        DataColumn(label: Text('批次跟踪')),
      ],
      getCells: (m) {
        return [
          DataCell(Text(m["PART_NO"].toString())),
          DataCell(Text(m["PART_DESC"].toString())),
          DataCell(Text(m["LOCATION_NO"].toString())),
          DataCell(Text(m["LOCATION_DESC"].toString())),
          DataCell(Text(m["WAREHOUSE"].toString())),
          DataCell(Text(m["LOCATION_TYPE"].toString())),
          DataCell(Text(m["LOT_BATCH_NO"].toString())),
          DataCell(Text(m["QTY_ONHAND"].toString())),
          DataCell(Text(m["QTY_RESERVED"].toString())),
          DataCell(Text(m["QTY_AVAILABLE"].toString())),
          DataCell(Text(m["UNIT_MEAS"].toString())),
          DataCell(Text(m["UNIT_CODE_DESC"].toString())),
          DataCell(Text(m["RECEIPT_DATE"].toString())),
          DataCell(Text(m["LAST_ACTIVITY_DATE"].toString())),
          DataCell(Text(m["LOT_TRACK_DESC"].toString())),
        ];
      },
    );
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              form,
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: buttonBar,
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() {
    partNo = null;
    formKey.currentState!.reset();
    tableKey.currentState?.pageTo(0);
    tableKey.currentState?.loadData(PageModel());
    setState(() {});
    // _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    if(!formKey.currentState!.validate()){
      return ;
    }
    // var url = 'http://192.168.20.50:8008/ShpordService.ashx?inAttr={"PART_NO":"$partNo"}&contract=ZTKD&contractKey=zU63CFzX%2fWcR1WHk4MmQT28GdN%2bFgzG5nTs269ZV7Uw%3d&procedureName=QUERY_INV_PART_IN_STOCK&userId=test';
    var url = '/ERP/ShpordService.ashx?inAttr={"PART_NO":"$partNo"}&contract=ZTKD&contractKey=zU63CFzX%2fWcR1WHk4MmQT28GdN%2bFgzG5nTs269ZV7Uw%3d&procedureName=QUERY_INV_PART_IN_STOCK&userId=test';
    Dio _dio = Dio();
    _dio.options.method = "GET";
    Response res = await _dio.request(url);
    var data = jsonDecode(res.data)["INV_PART_INFO"];
    List<Map<String, dynamic>> list = [];
    int start = (page.current - 1) * page.size;
    int end = page.current * page.size<data.length?page.current * page.size:data.length;
    for (var i = start;i < end;i++){
      Map<String, dynamic> map = data[i];
      list.add(map);
    }
    page.records = list;
    page.total = data.length;
    page.pages = data.length ~/ page.size + 1;
    tableKey.currentState!.loadData(page);
  }
}
